package com.xiaoyao.login.listener;

import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;

import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.function.Consumer;

/**
 * @Classname SpringApplicationListener
 * @Description TODO
 * @Date 2022/4/20 17:22
 * @Created by Lenovo
 */
public final class SpringApplicationListener implements ApplicationListener<ApplicationStartedEvent> {

    private static final Set<Consumer<ApplicationContext>> builtinListeners = Collections.synchronizedSet(new LinkedHashSet<>());

    private static ApplicationContext rootApplicationContext;

    public static ApplicationContext getRootApplicationContext() {
        return rootApplicationContext;
    }

    public static void addListener(Consumer<ApplicationContext> listener) {
        if (listener != null) {
            builtinListeners.add(listener);

            if (rootApplicationContext != null) {
                listener.accept(rootApplicationContext);
            }
        }
    }

    @SuppressWarnings("unchecked")
    public void onApplicationEvent(ApplicationStartedEvent event) {
        ApplicationContext context = event.getApplicationContext();
        if (rootApplicationContext == context) {
            return;
        }
        rootApplicationContext = context;

        Consumer<ApplicationContext>[] builtinCopy = builtinListeners.toArray(new Consumer[builtinListeners.size()]);
        for (Consumer<ApplicationContext> listener : builtinCopy) {
            listener.accept(context);
        }
    }
}
